package com.example.demo.controller;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.config.AuthAccess;
import com.example.demo.entity.Name;
import com.example.demo.entity.User;
import com.example.demo.mapper.LogMapper;
import com.example.demo.service.ILogService;
//import com.example.demo.service.TestAutowired;
import com.example.demo.utils.FileUploadService;
//import com.ice.tar.TarEntry;
//import com.ice.tar.TarInputStream;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
//import net.sf.sevenzipjbinding.*;
//import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
//import net.sf.sevenzipjbinding.simple.ISimpleInArchive;
//import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem;
//import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
//import de.innosystec.unrar.Archive;
//import de.innosystec.unrar.rarfile.FileHeader;

@Slf4j
@Api(tags = "测试框架")
@RestController
@RequestMapping("/manage/userInfo")
//@RequestMapping("/manage/userInfo")
public class TestController {

    @Autowired
    ILogService logService;

    @Value("${value}")
    private String value;
//    @PostMapping
//    @RequestMapping("/")
//    public String index() {
//        return "Hello springboot!";
//    }

    @ApiOperation("获取名字列表")
    @RequestMapping("/getName")
    public List<Name> getName(@RequestBody Map<String,Object> params,String a,@RequestParam Map<String,Object> params1) {
        System.out.println("getName");
        System.out.println(value);
        List<Name> result = logService.getName();
//        for (String s:
//                result) {
//            System.out.println(s);
//        }
        System.out.println(logService.getName().get(0));
        return logService.getName();
    }

    @RequestMapping("/postName")
    @ApiOperation("测试名字")
    public String postName(HttpServletRequest request){
        String a1 = request.getParameter("name1");
        System.out.println(a1);
//        logService.insertNames();
        return "post Name 后裔" +
                "!";
    }

    @RequestMapping("excelDownload")
    public void excelDownload(HttpServletResponse response) throws IOException {
        List<Name> nameList = this.getName(new HashMap<>(),new String(),new HashMap<>());
        this.excelDownload(nameList,Name.class,response);
    }
    public <T>  void excelDownload(List<T> list, Class<T> clazz, HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String sDate = df.format(new Date());

        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("数据导出"+sDate, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
//		EasyExcel.write(response.getOutputStream(), clazz).sheet("sheet1").doWrite(list);
        EasyExcel.write("d:\\1123.xlsx", clazz).sheet("sheet1").doWrite(list);
    }

    /**
     * MongoDB存储json格式数据
     *
     * json数据可以是JSONObject，也可以是JSONArray
     *
     * @param jsonObject
     * @return
     */
    @Autowired
    private MongoTemplate mongoTemplate;
    @PostMapping("/mongoAddJsonData")
    public void mongoAddJsonData(@RequestBody JSONObject jsonObject){
        this.mongoTemplate.insert(jsonObject, "mongo_json_test");
    }

    @Autowired
    LogMapper logMapper;
    @PostMapping("/pageTest")
    public IPage<Name> pageTest(){
        Integer currentPage = 1; //当前页数：显示第一页数据
        Integer pageSize = 2;    //每页显示多少：每页显示2条数据
        Page<Name> page = new Page<Name>(currentPage, pageSize);
        IPage<Name> resultList = logMapper.getPageName(page);
       return resultList;
    }
    @Autowired
    private FileUploadService fileUploadService;
    @PostMapping("/uploadTest")
    public void uploadTest(@RequestParam("file1")MultipartFile file) throws IOException {
        fileUploadService.upload(file);
    }
    @PostMapping("/unzip")
    public void unzip(@RequestParam("file1")MultipartFile upfile) throws IOException {
        File file = multipartFileToFile(upfile);	// 定义压缩文件名称
        File outFile = null ;	// 输出文件的时候要有文件夹的操作
        ZipFile zipFile = new ZipFile(file,  Charset.forName(System.getProperty("sun.jnu.encoding")));	// 实例化ZipFile对象
        ZipInputStream zipInput = null ;	// 定义压缩输入流
        OutputStream out = null ;	// 定义输出流，用于输出每一个实体内容
        InputStream input = null ;	// 定义输入流，读取每一个ZipEntry
        ZipEntry entry = null ;	// 每一个压缩实体
        zipInput = new ZipInputStream(new FileInputStream(file),Charset.forName("GBK")) ;	// 实例化ZIpInputStream
        while((entry = zipInput.getNextEntry())!=null){	// 得到一个压缩实体
            System.out.println("解压缩" + entry.getName() + "文件。") ;
            outFile = new File("d:" + File.separator +UUID.randomUUID()+ entry.getName()) ;	// 定义输出的文件路径
            if(!outFile.getParentFile().exists()){	// 如果输出文件夹不存在
                outFile.getParentFile().mkdir() ;	// 创建文件夹
            }
            if(!outFile.exists()){	// 判断输出文件是否存在
                outFile.createNewFile() ;	// 创建文件
            }
            input = zipFile.getInputStream(entry) ;	// 得到每一个实体的输入流
            out = new FileOutputStream(outFile) ;	// 实例化文件输出流
            int temp = 0 ;
            while((temp=input.read())!=-1){
                out.write(temp) ;
            }
            input.close() ;	// 关闭输入流
            out.close() ;	// 关闭输出流
        }
        input.close() ;
        System.out.println(1);
    }
    /**
     * 将MultipartFile转换为File
     * @param multiFile
     * @return
     */
    public static File multipartFileToFile(MultipartFile multiFile) {
        // 获取文件名
        String fileName = multiFile.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 若须要防止生成的临时文件重复,能够在文件名后添加随机码

        try {
            File file = File.createTempFile(fileName, prefix);
            multiFile.transferTo(file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解压rar
//     * @param sourceRarPath 需要解压的rar文件全路径
//     * @param destDirPath 需要解压到的文件目录
     * @throws Exception
     */
//    @RequestMapping("unrar")
//    public static void unrar(@RequestParam("file1")MultipartFile rarFile) throws Exception {
//
//        File sourceRar=multipartFileToFile(rarFile);
//        File destDir=new File("D:\\123");
//        Archive archive = null;
//        FileOutputStream fos = null;
//        System.out.println("Starting 开始解压...");
//        try {
//            archive = new Archive(sourceRar);
//            FileHeader fh = archive.nextFileHeader();
//            int count = 0;
//            File destFileName = null;
//            while (fh != null) {
//                System.out.println((++count) + ") " + fh.getFileNameString());
//                String compressFileName = fh.getFileNameString().trim();
//                destFileName = new File(destDir.getAbsolutePath() + "/" + compressFileName);
//                if (fh.isDirectory()) {
//                    if (!destFileName.exists()) {
//                        destFileName.mkdirs();
//                    }
//                    fh = archive.nextFileHeader();
//                    continue;
//                }
//                if (!destFileName.getParentFile().exists()) {
//                    destFileName.getParentFile().mkdirs();
//                }
//
//                fos = new FileOutputStream(destFileName);
//                archive.extractFile(fh, fos);
//                fos.close();
//                fos = null;
//                fh = archive.nextFileHeader();
//            }
//
//            archive.close();
//            archive = null;
//            System.out.println("Finished 解压完成!");
//        } catch (Exception e) {
//            throw e;
//        } finally {
//            if (fos != null) {
//                try {
//                    fos.close();
//                    fos = null;
//                } catch (Exception e) {
//                }
//            }
//            if (archive != null) {
//                try {
//                    archive.close();
//                    archive = null;
//                } catch (Exception e) {
//                }
//            }
//        }
//    }
//
//    /**
//     * 解压tar包
//     * @param tarSrcPath  要解压的tar包的绝对路径
//     * @param destPath    解压出的文件的存放目录
//     * @return list       tar里的文件集合
//     */
//    @RequestMapping("untar")
//    public static List<File> unTar(@RequestParam("file1")MultipartFile upfile) {
//
//        //返回tar里的文件集合
//        List<File> tarFileList = new ArrayList<File>();
//
//        InputStream inputstream = null;
//        OutputStream outputstream = null;
//        TarInputStream zis = null;
//        try {
//
//            File file = multipartFileToFile(upfile);
//            File tempFile = null;
//            inputstream = new FileInputStream(file);
//            zis = new TarInputStream(inputstream);
//            /*
//             * 关键在于这个TarEntry 的理解， 实际你的tar包里有多少文件就有多 少TarEntry
//             */
//            TarEntry tarEntry = null;
//            while ((tarEntry = zis.getNextEntry()) != null) {
//                tempFile = new File("d:\\123\\" + tarEntry.getName());
//                if(tempFile.exists()){
//                    tempFile.delete();
//                }
//                tempFile.createNewFile();
//
//                outputstream = new FileOutputStream(tempFile);
//                // 定一个缓存池 可以根据实际情况调整大小（事实证
//                // 明很有用）
//                byte[] buffer = new byte[1024 * 50];
//                while (true) {
//                    int readsize = zis.read(buffer);
//
//                    if (readsize <= 0) {
//                        break;
//                    }
//
//                    outputstream.write(buffer, 0, readsize);
//                    outputstream.flush();
//                }
//                tarFileList.add(tempFile);
//            }
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            try {
//                outputstream.flush();
//                inputstream.close();
//                zis.close();
//                outputstream.close();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//
//        }
//
//        return tarFileList;
//
//    }
//
//    @RequestMapping("un7z")
//    public static int un7z(@RequestParam("file1")MultipartFile upFile,String file7zPath) throws Exception {
//        File file7z = multipartFileToFile(upFile);
//        IInArchive archive;
//        RandomAccessFile randomAccessFile;
//        randomAccessFile = new RandomAccessFile(file7z, "r");
//        archive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile));
//        int numberOfItems = archive.getNumberOfItems();
//        ISimpleInArchive simpleInArchive = archive.getSimpleInterface();
//        for (final ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
//            final int[] hash = new int[] { 0 };
//            if (!item.isFolder()) {
//                ExtractOperationResult result;
//                final long[] sizeArray = new long[1];
//                result = item.extractSlow(new ISequentialOutStream() {
//                    public int write(byte[] data) throws SevenZipException {
//                        try {
//                            IOUtils.write(data,new FileOutputStream(new File("D:\\123\\"+ File.separator + item.getPath()),true));
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                        hash[0] ^= Arrays.hashCode(data); // Consume data
//                        sizeArray[0] += data.length;
//                        return data.length; // Return amount of consumed
//                    }
//                });
//                if (result == ExtractOperationResult.OK) {
//                    // logger.error("解压成功...." +String.format("%9X | %10s | %s",
//                    // hash[0], sizeArray[0], item.getPath()));
//                } else {
//                    // logger.error("解压失败：密码错误或者其他错误...." +result);
//                }
//            }
//        }
//        archive.close();
//        randomAccessFile.close();
//
//        return numberOfItems;
//    }
//    @RequestMapping("getNames")
//    public void getNames(HttpServletRequest request){
//        Enumeration<String> enumeration = request.getParameterNames();
//        String a = enumeration.nextElement();
//        while(a!=null&&a!=""){
//            System.out.println(a);
//        }
//    }

    @PostMapping("get")
    public static String getJsonData(JSONObject jsonParam) {
        StringBuffer sb=new StringBuffer();
        String resultJsonto = new String();
        try {
            // 创建url资源
            URL url = new URL("http://XXXXXXXXX");
            // 建立http连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置允许输出
            conn.setDoOutput(true);
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(100000);
            // 设置允许输入
            conn.setDoInput(true);
            // 设置不用缓存
            conn.setUseCaches(false);
            // 设置传递方式
            conn.setRequestMethod("POST");
            // 设置维持长连接
            conn.setRequestProperty("Connection", "Keep-Alive");
            // 设置文件字符集:
            conn.setRequestProperty("Charset", "UTF-8");
            // 转换为字节数组
            //byte[] data = (jsonParam.toString()).getBytes();
            byte[] data = jsonParam.toString().getBytes();
            // 设置文件长度
            conn.setRequestProperty("Content-Length", String.valueOf(data.length));
            // 设置文件类型:
            conn.setRequestProperty("contentType", "application/json");
            // 开始连接请求
            conn.connect();
            OutputStream out = new DataOutputStream(conn.getOutputStream()) ;
            // 写入请求的字符串
            out.write(jsonParam.toString().getBytes());
            out.flush();
            out.close();
            System.out.println(conn.getResponseCode());
            // 请求返回的状态
            if (HttpURLConnection.HTTP_OK == conn.getResponseCode()){
                System.out.println("连接成功");
                // 请求返回的数据
                InputStream in1 = conn.getInputStream();
                try {
                    String readLine=new String();
                    BufferedReader responseReader=new BufferedReader(new InputStreamReader(in1,"UTF-8"));
                    while((readLine=responseReader.readLine())!=null){
                        sb.append(readLine).append("\n");
                    }
                    responseReader.close();
                    String json = sb.toString();
                    //第一次解码

                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            } else {
                System.out.println("连接失败");
                InputStream error = conn.getErrorStream();
                String errorLine=new String();
                BufferedReader errorresponseReader=new BufferedReader(new InputStreamReader(error,"UTF-8"));
                while((errorLine=errorresponseReader.readLine())!=null){
                    sb.append(errorLine).append("\n");
                }
                errorresponseReader.close();
                String errorData = sb.toString();
                System.err.println("错误信息："+errorData);
            }
        } catch (Exception e) {
            System.out.println("error");
            e.printStackTrace();
        }
        return resultJsonto;
    }

        @RequestMapping("song")
        public void myCookie(HttpServletRequest request,HttpServletResponse response) {
            Cookie[] cookies = request.getCookies();
            if(cookies!=null)
            for (Cookie cookie : cookies) {
                System.out.println(cookie.getName() + "====" + cookie.getValue());
                if (cookie.getName().equals("student") && cookie.getValue().equals("songXianYang")) {
                    //执行相应的代码
                } else {
                    //否则执行什么
                }
            }
            Cookie cookie = new Cookie("student3", "songXianYang");
            //指定cookie绑定路径  setPath  在非springboot项目里需要添加项目的名称（request.getcontestpath（）+路径）
            cookie.setPath("/");
            //给cookie设置有效期  单位秒   setMaxAge
            cookie.setMaxAge(60*60*24);
            //把生成的cookie写到响应的客户端
            response.addCookie(cookie);
            HttpSession s= request.getSession();
            s.setMaxInactiveInterval(60*20);//单位秒
//            return "my cookie";
        }
    @RequestMapping("cookie")
    public String findAllCookie(HttpServletRequest request) {
        //从请求中获取cookie的name与value
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            System.out.println(cookie.getName() + "====" + cookie.getValue());
            if (cookie.getName().equals("student") && cookie.getValue().equals("songXianYang")) {
                //执行相应的代码
            } else {
                //否则执行什么
            }
        }
        return "从请求中获取cookie的name与value";
    }
    @Autowired
    private HttpServletResponse res;
    @GetMapping("/down")
    public void down() throws IOException {
        OutputStream os=null;
        os = res.getOutputStream();
        File src = new File("D:/fileTest.txt");
        InputStream inputStream = new FileInputStream(src);
        byte[] buf = new byte[(int)204800];
        int size ;
        long cnt = 0;
        while ((size=inputStream.read(buf))>0){
            cnt++;
            System.out.println(cnt + " =size=====>" + size);
            os.write(buf,0,size);
            os.flush();
        }
        os.close();
        inputStream.close();
    }

    @ApiOperation("Shiro登录认证")
    @PostMapping("/Shiro")
    public String login(@RequestBody JSONObject request) {
        String username = request.getString("username");
        String password = request.getString("password");
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try
        {
            subject.login(token);
            return "login success!";
        }
        catch (AuthenticationException e)
        {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage()))
            {
                msg = e.getMessage();
            }
            return msg;
        }

    }

    @Autowired
    User user;
    private static ApplicationContext context;

    private static User user1;
    private static int a;
//    @Autowired
//    LogMapper logMapper;
//    @Autowired
//    TestAutowired testAutowired;
    @GetMapping("/token")
    @ApiOperation("token获取")
    @AuthAccess(message = "token获取de测试注解展示！")
    public void print(){
//       AccessTokenUtils accessTokenUtils =new AccessTokenUtils();
//       String token = accessTokenUtils.getAccessToken();
////       System.out.println(token);
//        log.info("这是token获取");
////        context.getBean("setUser");
//        user1.getId();
//        System.out.println(a);
//        log.info("success");
        Map a = new HashMap();
        a.put("I_PrjID",1);
        a.put("I_DevAddr",1);
        a.put("I_RecID",1);
        a.put("I_CmdCount",136);
        a.put("I_DealType",1);
        a.put("I_DownCmd","司马光");
        System.out.println(a);
//        testAutowired.getName();
//        logMapper.query(a);
    }
}